﻿using System;
using System.Runtime.CompilerServices;

using Microsoft.AspNetCore.Http;

namespace System {
    public class EngineContext
    {
        #region Methods
        [MethodImpl(MethodImplOptions.Synchronized)]
        public static IEngine Create()
        {
            return Singleton<IEngine>.Instance ?? (Singleton<IEngine>.Instance = new AgileEngine());
        }
        public static void Replace(IEngine engine)
        {
            Singleton<IEngine>.Instance = engine;
        }

        #endregion

        #region Properties
        public static IEngine Current
        {
            get
            {
                if (Singleton<IEngine>.Instance == null)
                {
                    Create();
                }
                return Singleton<IEngine>.Instance;
            }
        }
        #endregion
    }

    public static class HttpContextCore
    {
        public static HttpContext Current { get => EngineContext.Current.Resolve<IHttpContextAccessor>().HttpContext; }
        /// <summary>
        /// 获取上下文值
        /// </summary>
        /// <param name="key">键</param>
        /// <returns></returns>
        public static T GetItem<T>(string key) {
            Current.Items.TryGetValue(key,out object res);
            return res.To<T>();
        }
        /// <summary>
        /// 设置上下文值
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        public static void SetItem(string key,string value) {
            if(Current.Items.ContainsKey(key)) {
                Current.Items.Remove(key);
            }
            Current.Items.Add(key,value);
        }
        /// <summary>
        /// 移除上下文值
        /// </summary>
        /// <param name="key"></param>
        public static void RemoveItem(string key) {
            if(Current.Items.ContainsKey(key)) {
                Current.Items.Remove(key);
            }

        }
    }
}
